

/**
 * <p>Title: UserSvcImpl</p>
 * <p>Description: UserSvc用户管理接口的</p>
 * <p>Copyright: Shanghai Batchsight Pharmaceutical Technologies, Inc. Copyright(c) 2016</p>
 * @author Chen Wei  & Huang Zhong wei
 * @version 1.0
 * <pre>
 * Histroy:2016-9-18  ZuoYeFeng  Create
 *</pre>
 */
package cn.jhg.account.service;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import cn.jhg.account.entity.AuditTrailObject;
import cn.jhg.account.entity.AuditTrailRecord;
import cn.jhg.account.entity.AuditTrailType;
import cn.jhg.account.entity.User;
import cn.jhg.account.entity.UserStatus;
import cn.jhg.account.entity.UserGroup;
import cn.jhg.account.persist.UserDao;
import cn.jhg.account.persist.UserGroupDao;
import cn.jhg.account.service.AuditTrailSvc;
import cn.jhg.account.util.SequenceProducer;
import cn.jhg.account.util.ServiceResult;

@Service("userSvc")
@Transactional
public class UserSvcImpl implements UserSvc {

	@Resource
	private UserDao userDao;
	@Resource
	private SequenceProducer sequenceProducer;
	@Resource
	private AuditTrailSvc auditTrailSvc;
	@Resource
	private UserGroupDao userGroupDao;
	
	private Logger logger = LoggerFactory.getLogger(UserSvcImpl.class);

	/**
	 * <p>Function: getUserById</p>
	 * <p>Description: 调用dao的getUserById方法获取对应用户</p>
	 * @param uid 用户ID值
	 * @return ServiceResult<User> 返回User对象
	 */
	@Override
	public ServiceResult<User> getUserById(int uid, int iuid) {
		ServiceResult<User> proxyResult = new ServiceResult<User>();
		try {
			User user = userDao.getUserById(uid);
			if (user == null) {
				proxyResult.setErrorCode(217661241);// 此ID的用户不存在
				logger.error("[ERR217661241] 此ID的用户不存在"+proxyResult);
			} else {
				proxyResult.setErrorCode(0);// 查询成功
				proxyResult.setData(user);
				logger.info("[INF221710860] getUserById查询成功！");
			}
			return proxyResult;
			
		} catch (Exception e) {
			proxyResult.setErrorCode(218089060);
			logger.error("[ERR218089060] 根据ID查询失败" + e.getMessage());
			TransactionAspectSupport.currentTransactionStatus( ).setRollbackOnly();
			return proxyResult;
		}
	}

	/**
	 * <p>Function: getUserByAccount</p>
	 * <p>Description: 调用dao的getUserByAccount方法获取对应用户</p>
	 * @param account 用户名
	 * @return ServiceResult<User> 返回用户对象
	 */
	@Override
	public ServiceResult<User> getUserByAccount(String account, int iuid) {
		ServiceResult<User> proxyResult = new ServiceResult<User>();
		try {
			User user = userDao.getUserByAccount(account);
			if (user == null) {
				proxyResult.setErrorCode(217662271);// 此用户名不存在
				logger.error("[ERR217662271] 此ID的用户不存在");
			} else {
				proxyResult.setErrorCode(0);
				proxyResult.setData(user);
				logger.info("[INF221710862] getUserByAccount查询成功！");
			}
			return proxyResult;
		} catch (Exception e) {
			proxyResult.setErrorCode(218089088);
			logger.error("[ERR218089088] 根据account查询失败" + e.getMessage());
			TransactionAspectSupport.currentTransactionStatus( ).setRollbackOnly();
			return proxyResult;
		}
	}

	/**
	 * <p>Function: findUserByName</p>
	 * <p>Description: 调用dao的findUserByName方法获取对应用户</p>
	 * @param condition 用户名称 name
	 * @return ServiceResult<List> 返回用户对象集合
	 */
	@Override
	public ServiceResult<List<Integer>> findUserByName(String condition, int iuid) {
		ServiceResult<List<Integer>> proxyResult = new ServiceResult<List<Integer>>();
		try {
			String name = "%" + condition + "%";
			List<Integer> set = userDao.findUserByName(name);
			if (set.isEmpty()) {
				proxyResult.setErrorCode(217662289);// 此name的用户不存在
				logger.error("[ERR217662289] 此name的用户不存在");
			} else {
				proxyResult.setErrorCode(0);
				proxyResult.setData(set);
				logger.info("[INF221710923] findUserByName查询成功！");
			}
			return proxyResult;
		} catch (Exception e) {
			proxyResult.setErrorCode(218089106);
			logger.error("[ERR218089106] 根据name模糊查询失败" + e.getMessage());
			TransactionAspectSupport.currentTransactionStatus( ).setRollbackOnly();
			return proxyResult;
		}
	}

	/**
	 * <p>Function: addUser</p>
	 * <p> Description: 调用dao的addUser方法添加用户</p> 
	 * @param user          需要添加的对象
	 * @return ServiceResult<Integer> 状态值和ID
	 */
	@Override
	public ServiceResult<Integer> addUser(User user, int sid, int iuid) {
		ServiceResult<Integer> proxyResult = new ServiceResult<Integer>();
		try {
			User u = userDao.getUserByAccount(user.getAccount());
			if (u == null) { //用戶名不存在
				int id = sequenceProducer.nextval("t_ibcp_user");
				user.setId(id);
				user.setStatus(0);
				user.setPassword("password");
				user.setPwdValidDate(new Timestamp(System.currentTimeMillis()));
				userDao.addUser(user);
				proxyResult.setData(id);
				proxyResult.setErrorCode(0);
				logger.info("[INF221710952] addUser成功！");
				// 添加审计追踪记录
				AuditTrailRecord atRecord = new AuditTrailRecord();
				atRecord.setSid(sid); // 签名 id
				atRecord.setUid(iuid); // 用户 id
				atRecord.setLid(100);
				atRecord.setTid(AuditTrailType.AddUser.GetId()); // 审计追踪类型 id
				atRecord.setOtid(AuditTrailObject.User.getId());    // 审计追踪对象 id

				Document metadata = new Document(); // 审计追踪元数据
				metadata.append("UserId", user.getId());
				metadata.append("Account", user.getAccount());
				metadata.append("UserName",  user.getName());
				atRecord.setMeta(metadata);
				
				auditTrailSvc.addRecord(atRecord);
			} else {//if语句结束
				proxyResult.setErrorCode(217662893);// 此用户名已经存在
				logger.error("[ERR217662893] 此用户名已经存在");
			}
			return proxyResult;
		} catch (Exception e) {//try 语句结束
			proxyResult.setErrorCode(218089129);
			logger.error("[ERR218089129] 添加用户失败" + e.getMessage());
			TransactionAspectSupport.currentTransactionStatus( ).setRollbackOnly();
			return proxyResult;
		}
	}

	/**
	 * <p> Function: updateUser </p>
	 * <p> Description: 调用dao的updateUser方法修改用户</p>
	 * @param user           需要修改的对象
	 * @return ServiceResult<Integer> 状态值为是否修改成功
	 */
	@Override
	public ServiceResult<Integer> updateUser(User user, int sid, int iuid) {
		ServiceResult<Integer> proxyResult = new ServiceResult<Integer>();
		try {
			userDao.updateUser(user);
			proxyResult.setErrorCode(0);// 成功	
			logger.info("[INF221710986] updateUser成功！");
			
			// 添加审计追踪记录
			AuditTrailRecord atRecord = new AuditTrailRecord();
			atRecord.setSid(sid); // 签名 id
			atRecord.setUid(iuid); // 用户 id
			atRecord.setLid(100);
			atRecord.setTid(AuditTrailType.UpdateUser.GetId()); // 审计追踪类型 id
			atRecord.setOtid(AuditTrailObject.User.getId());    // 审计追踪对象 id

			Document metadata = new Document(); // 审计追踪元数据
			metadata.append("UserId", user.getId());
			metadata.append("Account", user.getAccount());
			metadata.append("UserName",  user.getName());
			atRecord.setMeta(metadata);
			auditTrailSvc.addRecord(atRecord);
			return proxyResult;
		} catch (Exception e) {
			proxyResult.setErrorCode(218089157);
			logger.error("[ERR218089157] 修改用户失败" + e.getMessage());
			TransactionAspectSupport.currentTransactionStatus( ).setRollbackOnly();
			return proxyResult;
		}
	}

	/**
	 * <p>Function: deleteUser</p>
	 * <p> Description: 调用dao的deleteUser方法删除用户 </p>
	 * @param uid           需要删除的对象的uid
	 * @return ServiceResult<Integer> 状态值为是否删除成功
	 */
//	@Override
//	public ServiceResult<Integer> deleteUser(int uid, int iuid) {
//		ServiceResult<Integer> proxyResult = new ServiceResult<Integer>();
//		try {
//			User u = userDao.getUserById(uid);
//			if (u == null) {
//				proxyResult.setErrorCode(217663459);// 此Id的用户不存在
//				logger.error("[ERR217663459] 此Id用户不存在");
//			} else {
//				userDao.deleteUser(uid);
//				proxyResult.setErrorCode(0);// 成功
//				logger.info("[INF221711019] deleteUser成功！");
//			}
//			return proxyResult;
//		} catch (Exception e) {
//			proxyResult.setErrorCode(218089178);
//			logger.error("[ERR218089178] 删除用户失败" + e.getMessage());
//			return proxyResult;
//		}
//	}

	/**
	 * <p> Function: invalidateUser </p>
	 * <p> Description: 调用dao的invalidate方法修改用户状态</p>
	 * @param uid            需要修改对象的uid
	 * @return ServiceResult<Integer> 状态值为是否修改成功
	 */
	@Override
	public ServiceResult<Integer> invalidateUser(int uid, int sid, int iuid) {
		ServiceResult<Integer> serviceResult = new ServiceResult<Integer>();
		try {
			User user = userDao.getUserById(uid);
			int status = user.getStatus();
			int lock = status | 16;// 按位或操作，16对应00010000，第四位为5
			user.setStatus(lock);
			userDao.invalidateUser(user);
			serviceResult.setErrorCode(0);
			serviceResult.setData(lock);
			logger.info("[INF221711045] invalidateUser成功！");
			// 添加审计追踪记录
			AuditTrailRecord atRecord = new AuditTrailRecord();
			atRecord.setSid(sid); // 签名 id
			atRecord.setUid(iuid); // 用户 id
			atRecord.setLid(100);
			atRecord.setTid(AuditTrailType.InvalidateUser.GetId()); // 审计追踪类型 id
			atRecord.setOtid(AuditTrailObject.User.getId());    // 审计追踪对象 id
			
			Document metadata = new Document(); // 审计追踪元数据
			metadata.append("UserId", user.getId());
			metadata.append("Account", user.getAccount());
			metadata.append("UserName",  user.getName());
			
			//获取用户所在组的信息
			List<Integer> ugidList=userDao.getUserGroup(uid);
			for(int i:ugidList){
				int ugid=i;
				UserGroup userGroup=userGroupDao.getUserGroupById(ugid);
				Map<String,Integer> map=new HashMap<String,Integer>();
				map.put("uid", uid);
				map.put("ugid", ugid);
				userGroupDao.deleteMember(map);//删除失效用户
				metadata.append("UserGroupId",  userGroup.getId());
				metadata.append("UserGroupName",  userGroup.getName());
			}
			atRecord.setMeta(metadata);
			auditTrailSvc.addRecord(atRecord);
			return serviceResult;
		} catch (Exception e) {//try 语句结束
			serviceResult.setErrorCode(218089194);// 失效用户失败
			logger.error("[ERR218089194] 失效用户失败" + e.getMessage());
			TransactionAspectSupport.currentTransactionStatus( ).setRollbackOnly();
			return serviceResult;
		}
}
	/**
	 * <p>Function: logIn </p>
	 * <p> Description: 调用dao的logIn方法登陆</p> 
	 * @param account            用户名
	 * @param pwd            用户密码
	 * @return ServiceResult<Integer> 状态值为是否登陆成功
	 */
	/*
	 * @Override public ServiceResult<Integer> logIn(String account, String
	 * pwd,int iuid){ ServiceResult<Integer> proxyResult=new
	 * ServiceResult<Integer>(); try{ User
	 * user=userDao.getUserByAccount(account);//判断用户名是否存在 Map<String,String>
	 * map=new HashMap<String,String>(); map.put("account", account);
	 * map.put("password",pwd); User u=userDao.logIn(map); if(user==null){
	 * proxyResult.setErrorCode(218085432);//用户名不存在
	 * logger.error("[ERR218181218]用户名不存在"); }else if(u==null){
	 * proxyResult.setErrorCode(218085451);//密码错误
	 * logger.error("[ERR218181297]密码错误"); }else{
	 * proxyResult.setErrorCode(0);//成功 proxyResult.setData(u.getId()); } return
	 * proxyResult; }catch(Exception e){
	 * logger.error("[ERR218089220]登录用户失败",ExceptionUtils.getFullStackTrace(e));
	 * throw new RuntimeException("登录用户失败",e); } }
	 */

	/**
	 * <p> Function: getUserGroup </p>
	 * <p> Description: 调用dao的getUserGroup方法修改有效期 </p>
	 * @param ID            用户ID
	 * @return ServiceResult<List<Integer>> 状态值和List集合成功
	 */
	@Override
	public ServiceResult<List<Integer>> getUserGroup(int uid, int iuid) {
		ServiceResult<List<Integer>> proxyResult = new ServiceResult<List<Integer>>();
		try {
			List<Integer> set = userDao.getUserGroup(uid);
			proxyResult.setData(set);
			proxyResult.setErrorCode(0);// 成功
			logger.info("[INF221711069] getUserGroup成功！");
			return proxyResult;
		} catch (Exception e) {
			proxyResult.setErrorCode(218089237);
			logger.error("[ERR218089237] 获得用户组失败" + e.getMessage());
			TransactionAspectSupport.currentTransactionStatus( ).setRollbackOnly();
			return proxyResult;
		}
	}

	/**
	 * <p>Function: findUser </p>
	 * <p>Description: 调用dao的findUser方法修改有效期 </p> 
	 * @param ID            用户ID
	 * @return ServiceResult<List<Integer>> 状态值和List集合成功
	 */
	@Override
	public ServiceResult<List<Integer>> findUser(String account, String name, UserStatus[] status, int iuid) {
		// account like %#{account}% and name like %#{name}% and (status&8)>0
		// and (status&16)=0
		// -- status&8 > 0 判断是否锁定
		// -- status&16 = 0 判断是否未失效
		ServiceResult<List<Integer>> result=new ServiceResult<List<Integer>>();
		String sql = "select id from t_ibcp_user";
		//判断都为空
		if ((account == null || account == "") && (name == null || name == "" )&&(status == null||status.length==0)) {
			//do nothing
		} else {
			sql += " where ";
			//账号不为空
			if (account != null && account != "") {
				sql += " account like '%" + account+"%'";
			}else{
				sql +=" account like '%%' ";
			}
			//name不为空
			if (name != null && name != "") {
				sql += " and name like '%" + name+"%'";
			}else{
				sql += " and name like '%%' ";
			}	
			//状态不为空且包含两种状态
			if(status.length==2){
					for (int i = 0; i < status.length; i++) {
						switch (status[i]) {
						case Locked:
							sql += " and (status&8)> 0";
							break;
						case Unlocked:
							sql += " and (status&8)= 0";
							break;
						case Invalid:
							sql += " and (status&16)>0";
							break;
						case Valid:
							sql += " and (status&16)=0";
							break;
						default:
							result.setErrorCode(221707165);
							logger.error("[ERR221707165] 状态错误");
							return result;
						}
					}
					}else if(status.length==1){
						//状态不为空 一种状态
						for (int i = 0; i < status.length; i++) {
							switch (status[i]) {
							case Locked:
								sql += "and  (status&8)> 0";
								break;
							case Invalid:
								sql += "and  (status&16)>0";
								break;
							case Unlocked:
								sql += "and  (status&8)= 0";
								break;
							case Valid:
								sql += "and  (status&16)=0";
								break;
							default:
								result.setErrorCode(221707165);
								logger.error("[ERR221707165] 状态错误");
								return result;
							}//switch 语句结束
						}//for循环语句结束
					}//else 内嵌套if-elseif语句结束
				}//else 语句结束
		Map<String,String> map=new HashMap<String,String>();
		map.put("sql", sql);
		System.out.println(sql);
		try{
		List<Integer> set=userDao.findUser(map);
		result.setErrorCode(0);
		result.setData(set);
		return result;
		} catch (Exception e) {//try 语句结束
			result.setErrorCode(221707168);
			logger.error("[ERR221707168] 状态查找用户失败" + e.getMessage());
			TransactionAspectSupport.currentTransactionStatus( ).setRollbackOnly();
			return result;
		}

	}

	@Override
	public ServiceResult<List<User>> findUsers(String account, String name, UserStatus[] status, int iuid) {
		ServiceResult<List<User>> result=new ServiceResult<List<User>>();
		String sql ="select id,name,email,telephone,pwd_valid_date,status,account, "
				+ "CASE WHEN status&8>0 THEN '锁定' ELSE '未锁定' END AS locked, "
				+ "CASE WHEN status&16>0 THEN '失效' ELSE '未失效' END AS valid "
				+ "from t_ibcp_user";
		//判断都为空
		if ((account == null ||"".equals(account)) && (name == null || "".equals(name) )&&(status == null||status.length==0)) {
			//do nothing
		} else {
			sql += " where ";
			//账号不为空
			if (account != null && !"".equals(account)) {
				sql += " account like '%" + account+"%'";
			}else{
				sql +=" account like '%%' ";
			}
			//name不为空
			if (name != null && !"".equals(name)) {
				sql += " and name like '%" + name+"%'";
			}else{
				sql += " and name like '%%' ";
			}	
			//状态不为空且包含两种状态
			if(status.length==2){
				for (int i = 0; i < status.length; i++) {
					switch (status[i]) {
					case Locked:
						sql += " and (status&8)> 0";
						break;
					case Unlocked:
						sql += " and (status&8)= 0";
						break;
					case Invalid:
						sql += " and (status&16)>0";
						break;
					case Valid:
						sql += " and (status&16)=0";
						break;
					default:
						result.setErrorCode(221707165);
						logger.error("[ERR221707165] 状态错误");
						return result;
					}
				}
			}else if(status.length==1){
				//状态不为空 一种状态
				for (int i = 0; i < status.length; i++) {
					switch (status[i]) {
					case Locked:
						sql += "and  (status&8)> 0";
						break;
					case Invalid:
						sql += "and  (status&16)>0";
						break;
					case Unlocked:
						sql += "and  (status&8)= 0";
						break;
					case Valid:
						sql += "and  (status&16)=0";
						break;
					default:
						result.setErrorCode(221707165);
						logger.error("[ERR221707165] 状态错误");
						return result;
					}//switch语句结束
				}//for 循环结束
			}//外层else内的if-elseif语句结束
		}//外层else语句结束
		Map<String,String> map=new HashMap<String,String>();
		map.put("sql", sql);
		System.out.println(sql);
		try{
		List<User> set=userDao.findUsers(map);
		result.setErrorCode(0);
		result.setData(set);
		logger.info("[INF221711101] findUser成功！");
		return result;
		} catch (Exception e) {//try 语句结束
			result.setErrorCode(221707168);
			logger.error("[ERR221707168] 状态查找用户失败" + e.getMessage());
			TransactionAspectSupport.currentTransactionStatus( ).setRollbackOnly();
			return result;
		}
	}
	
	/**
	 * <p> Function: findUserExist </p>
	 * <p> Description: 调用dao的findUserExist方法获取不在特定用户组的用户 </p>
	 * @param ugid            用户组id
	 * @return ServiceResult<List<User>> 状态值和List集合成功
	 */
	@Override
	public ServiceResult<List<User>> findUserExist(int ugid, int iuid) {
		ServiceResult<List<User>> result=new ServiceResult<List<User>>();
		try{
			List<User> users=userDao.findUserExist(ugid);
			result.setErrorCode(0);
			result.setData(users);
			logger.info("[INF221967333] findUserExist成功！");
			return result;
		}catch(Exception e){
			result.setErrorCode(221967336);
			logger.error("[ERR221967336] 查找不在特定用户组的用户失败" + e.getMessage());
			TransactionAspectSupport.currentTransactionStatus( ).setRollbackOnly();
			return result;
		}
	}

}
